package com.zhentao.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.Role;
import com.zhentao.pojo.User;
import com.zhentao.pojo.UserRole;
import com.zhentao.service.impl.RoleServiceImpl;
import com.zhentao.service.impl.UserRoleServiceImpl;
import com.zhentao.service.impl.UserServiceImpl;
import com.zhentao.util.Result;
import com.zhentao.vo.UserPageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author "杨旭朋"
 * @ClassName: CustomerController
 * @date 2025年07月31日 16:20
 */
@RestController
@RequestMapping("customer")
public class CustomerController {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private UserRoleServiceImpl userRoleService;
    @Autowired
    private RoleServiceImpl roleService;

    @PostMapping("UserList")
    public Result<Page<User>> UserList(@RequestBody UserPageVo UserPageVo) {
        // 添加空值检查
        if (UserPageVo == null) {
            UserPageVo = new UserPageVo();
        }
        
        // 确保分页参数有合理的默认值
        Integer pageNum = UserPageVo.getPageNum();
        Integer pageSize = UserPageVo.getPageSize();
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        
        LambdaQueryWrapper<User> like = Wrappers.<User>lambdaQuery()
                .like(UserPageVo.getUsername() != null && !UserPageVo.getUsername().isEmpty(), User::getUsername, UserPageVo.getUsername())
                .like(UserPageVo.getRealName() != null && !UserPageVo.getRealName().isEmpty(), User::getRealName, UserPageVo.getRealName())
                .eq(UserPageVo.getRid() != null && UserPageVo.getRid() != 0, User::getId, UserPageVo.getRid())
                .gt(UserPageVo.getStartTime() != null && !UserPageVo.getStartTime().isEmpty(), User::getCreateTime, UserPageVo.getStartTime())
                .lt(UserPageVo.getEndTime() != null && !UserPageVo.getEndTime().isEmpty(), User::getCreateTime, UserPageVo.getEndTime());
        
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), like);
        
        for (User record : page.getRecords()) {
            UserRole one = userRoleService.getOne(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, record.getId()));
            if (one != null) {
                Role one1 = roleService.getOne(Wrappers.<Role>lambdaQuery().eq(Role::getId, one.getRoleId()));
                if (one1 != null) {
                    record.setRoleName(one1.getName());
                    record.setRid(Integer.parseInt(one.getRoleId().toString()));
                }
            }
        }
        return Result.success(page);
    }

    @GetMapping("RoleList")
    public Result<List<Role>> RoleList() {
        try {
            List<Role> roles = roleService.list();
            return Result.success(roles);
        } catch (Exception e) {
            return Result.error("获取角色列表失败：" + e.getMessage());
        }
    }

    @PostMapping("UserStatusAlt")
    public Result<String> UserStatusAlt(@RequestParam("uid") int uid) {
        try {
            User byId = userService.getById(uid);
            if (byId == null) {
                return Result.error("用户不存在");
            }
            
            int status = 3;
            if (byId.getStatus() == 0) {
                status = 1;
            } else {
                status = 0;
            }
            byId.setStatus(status);
            
            UserRole userRole = userRoleService.getOne(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, uid));
            if (userRole != null && userRole.getRoleId() == 1) {
                return Result.error("管理员不能被禁用");
            }
            
            userService.updateById(byId);
            String message = byId.getStatus() == 1 ? "启用成功" : "禁用成功";
            return Result.success(message);
        } catch (Exception e) {
            return Result.error("修改用户状态失败：" + e.getMessage());
        }
    }

    @PostMapping("UserDel")
    public Result<String> UserDel(@RequestParam("uid") int uid) {
        try {
            UserRole one = userRoleService.getOne(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, uid));
            if (one != null && one.getRoleId() == 1) {
                return Result.error("管理员不能被删除");
            }
            
            if (one != null) {
                userRoleService.removeById(one);
            }
            boolean success = userService.removeById(uid);
            return success ? Result.success("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            return Result.error("删除用户失败：" + e.getMessage());
        }
    }

    @PostMapping("UserAdd")
    public Result<String> UserAdd(@RequestBody User user) {
        try {
            if (user == null) {
                return Result.error("用户信息不能为空");
            }
            
            User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
            if (null != one) {
                return Result.error("用户已存在");
            }
            
            User save = new User();
            save.setUsername(user.getUsername());
            save.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
            save.setEmail(user.getEmail());
            save.setPhone(user.getPhone());
            save.setRealName(user.getRealName());
            save.setStatus(user.getStatus());
            save.setImages(null);
            save.setCreateTime(new Date());
            
            userService.save(save);
            
            UserRole userRole = new UserRole();
            userRole.setUserId(save.getId());
            userRole.setRoleId((long) user.getRid());
            userRoleService.save(userRole);
            
            return Result.success("注册成功");
        } catch (Exception e) {
            return Result.error("添加用户失败：" + e.getMessage());
        }
    }

    @PostMapping("UserUpdate")
    public Result<String> UserUpdate(@RequestBody User user) {
        try {
            if (user == null || user.getId() == null) {
                return Result.error("用户信息不能为空");
            }
            
            User byId = userService.getById(user.getId());
            if (byId == null) {
                return Result.error("用户不存在");
            }
            
            user.setPassword(byId.getPassword());
            int rid = user.getRid();
            
            UserRole one = userRoleService.getOne(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, user.getId()));
            if (one != null) {
                one.setRoleId((long) rid);
                boolean b = userRoleService.updateById(one);
                boolean b1 = userService.updateById(user);
                return (b && b1) ? Result.success("修改成功") : Result.error("修改失败");
            } else {
                return Result.error("用户角色信息不存在");
            }
        } catch (Exception e) {
            return Result.error("修改用户失败：" + e.getMessage());
        }
    }
}
